<template>
  <div>
    <SearchForm
      @search="onSearch"
      @reset="onReset"
      :search-list="searchList"
      :search-params="searchParams"
    >
      <template #button>
        <el-button type="primary" size="mini" @click="onAdd(0)">新增分类</el-button>
      </template>
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-box">
          <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            max-height="500px"
            :data="tableData"
            row-key="id"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            @selection-change="onSelect"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column align="center" label="ID" prop="id" width="80" />
            <el-table-column align="center" label="分类名称" prop="name" />
            <el-table-column align="center" label="上级分类" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.parent_id === 0">顶级分类</span>
                <span v-else>{{ getParentName(scope.row.parent_id) }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="排序" prop="sort" width="80" />
            <el-table-column align="center" label="图标" width="100">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.icon"
                  style="width: 40px; height: 40px"
                  :src="scope.row.icon"
                  :preview-src-list="[scope.row.icon]"
                ></el-image>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" prop="status" width="100">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
                <el-tag type="danger" v-else>禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="180">
              <template slot-scope="scope">
                {{ scope.row.create_time | dateFormat }}
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="onAdd(scope.row.id)">添加子分类</el-button>
                <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <div class="page-box">
        <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
        />
      </div>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        :loading="formLoading"
        @save="onSaveCategory"
        @close="dialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import { http, uploadFile } from "@/api";

export default {
  name: "OfficeCategoryIndex",
  mixins: [crud],
  data() {
    return {
      request: http.officeCategory,
      searchList: [
        {
          label: '分类名称',
          prop: 'name',
          name: 'input',
          clearable: true
        },
        {
          label: '上级分类',
          prop: 'parent_id',
          name: 'select',
          clearable: true,
          options: [
            { label: '顶级分类', value: 0 }
          ]
        }
      ],
      searchParams: {
        name: '',
        parent_id: ''
      },
      defaultParams: {
        type: 1,
      },
      categoryOptions: [],
      dialogTitle: '添加分类',
      dialogVisible: false,
      formLoading: false,
      parentId: 0,
      ruleForm: {
        type: 1,
        name: '',
        parent_id: 0,
        sort: 0,
        status: 1,
        icon: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      formList: [
        {
          label: '分类名称',
          prop: 'name',
          name: 'input',
          placeholder: '请输入分类名称',
          colSpan: 24
        },
        {
          label: '上级分类',
          prop: 'parent_id',
          name: 'select',
          placeholder: '请选择上级分类',
          options: [
            { label: '顶级分类', value: 0 }
          ],
          colSpan: 24
        },
        {
          label: '排序',
          prop: 'sort',
          name: 'number',
          min: 0,
          colSpan: 24
        },
        {
          label: '图标',
          prop: 'icon',
          name: 'image',
          colSpan: 24
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          activeValue: 1,
          inactiveValue: 0,
          activeText: '启用',
          inactiveText: '禁用',
          colSpan: 24
        }
      ]
    };
  },
  mounted() {
    this.loadCategoryOptions();
  },
  methods: {
    loadCategoryOptions() {
      http.officeCategory.list({ type: 1 }).then(res => {
        const options = [{ label: '顶级分类', value: 0 }];
        res.data.forEach(item => {
          options.push({
            label: item.name,
            value: item.id
          });
        });
        this.categoryOptions = res.data;
        this.searchList[1].options = options;
        this.formList[1].options = options;
      });
    },
    getParentName(parentId) {
      const parent = this.categoryOptions.find(item => item.id === parentId);
      return parent ? parent.name : '';
    },
    onAdd(parentId = 0) {
      this.dialogTitle = parentId === 0 ? '添加分类' : '添加子分类';
      this.dialogVisible = true;
      this.ruleForm = {
        type: 1,
        name: '',
        parent_id: parentId,
        sort: 0,
        status: 1,
        icon: '',
        description: ''
      };
    },
    onEdit(row) {
      this.dialogTitle = '编辑分类';
      this.dialogVisible = true;
      this.ruleForm = { ...row };
    },
    async onSaveCategory() {
      this.formLoading = true;
      try {
        if (this.ruleForm.id) {
          await http.officeCategory.update(this.ruleForm.id, this.ruleForm);
        } else {
          await http.officeCategory.create(null, this.ruleForm);
        }
        this.$message.success('保存成功');
        this.dialogVisible = false;
        this.onSearch();
        this.loadCategoryOptions();
      } catch (error) {
        console.error(error);
        this.$message.error('保存失败');
      } finally {
        this.formLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}
.page-box {
  margin-top: 20px;
  text-align: right;
}
</style>
